package cn.ybk.org.service.impl;

import cn.ybk.basic.service.impl.BaseServiceImpl;
import cn.ybk.org.domain.Department;
import cn.ybk.org.service.DepartmentService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {

    // 业务 多级联查
    @Override
    public List<Department> tree() {
//         创建一个空list集合
        List<Department> result = new ArrayList<>();
        // 调用查询全部数据（能直接调用findAll方法）
        List<Department> all = findAll();
        // 转换为Stream流，弄在map集合中，key 是department中的id，value是，
        Map<Long, Department> collect = all.stream().
                collect(Collectors.toMap(Department::getId, dept -> dept));
        for (Department dept : all) {
            if (dept.getParentId() == null) {
                result.add(dept);
            } else {
                Department department = collect.get(dept.getParentId());
                if (department != null) {
                    department.getChildren().add(dept);
                }
            }
        }
        return result;
    }


}
